// 学生信息管理
function initStudentList() {
  // 获取学生信息列表
  axios({
    url: '/student/list',
    method: 'GET'
  }).then(({ data: res }) => {
    if (res.code === 0) {
      // console.log(res)
      // 数据渲染
      tbody.innerHTML = res.data.map(ele => `
      <tr>
        <th scope="row">${ ele.id }</th>
        <td>${ ele.name }</td>
        <td>${ ele.age }</td>
        <td>${ ele.sex }</td>
        <td>${ ele.group }</td>
        <td>${ ele.phone }</td>
        <td>${ ele.salary }</td>
        <td>${ ele.truesalary }</td>
        <td>${ ele.province + ele.city + ele.county }</td>
        <td>
          <button data-id="${ ele.id }" type="button" class="btn btn-primary btn-sm update" data-bs-toggle="modal" data-bs-target="#updateModal">修改</button>
          <button data-id="${ ele.id }" type="button" class="btn btn-danger btn-sm del">删除</button>
        </td>
      </tr>
     `).join('')
    }
  })
}

const tbody = document.querySelector('tbody')
// 页面加载获取数据
initStudentList()

// 删除数据 事件委托实现
tbody.addEventListener('click', function (e) {
  if (!e.target.classList.contains('del')) return
  if (!confirm('是否确认删除学生信息？')) return
  let id = e.target.getAttribute('data-id')
  axios({
    method: 'DELETE',
    url: '/student/delete',
    params: { id }
  }).then(({ data: res }) => {
    if (res.code === 0) {
      alert(res.message)
      initStudentList()
    }
  })
})

// 省市县三级联动
const addForm = document.querySelector('.add-form')
const updateForm = document.querySelector('.update-form')
initPlace(addForm)
initPlace(updateForm)

function initPlace(form) {
  // 根据不同的表单获取不同的select
  const province = form.querySelector('[name="province"]')
  const city = form.querySelector('[name="city"]')
  const county = form.querySelector('[name="county"]')
  // 获取省
  axios({
    url: '/geo/province',
    method: 'GET'
  }).then(({ data: res }) => {
    province.innerHTML += res.map(ele => `<option value="${ ele }">${ ele }</option>`).join('')
  })
  // 省改变后触发市级变化
  province.addEventListener('change', function () {
    // 没有选择省，清空区县
    county.innerHTML = '<option selected value="">--区/县--</option>'
    // 市需要判断
    if (province.value === '') {
      city.innerHTML = '<option selected value="">--市--</option>'
      return
    }
    // 获取市
    axios({
      url: '/geo/city',
      method: 'GET',
      params: { pname: province.value }
    }).then(({ data: res }) => {
      city.innerHTML += res.map(ele => `<option value="${ ele }">${ ele }</option>`).join('')
    })
  })
  // 市级变化后触发县区级变化
  city.addEventListener('change', function () {
    if (city.value === '') {
      county.innerHTML = '<option selected value="">--区/县--</option>'
      return
    }
    // 获取区县
    axios({
      url: '/geo/county',
      method: 'GET',
      params: {
        pname: province.value,
        cname: city.value
      }
    }).then(({ data: res }) => {
      county.innerHTML += res.map(ele => `<option value="${ ele }">${ ele }</option>`).join('')
    })
  })
}

// 添加学生信息
addForm.addEventListener('submit', function (e) {
  e.preventDefault()
  axios({
    url: '/student/add',
    method: 'POST',
    data: $(this).serialize()
  }).then(({ data: res }) => {
    if (res.code === 0) {
      alert(res.message)
      // 关闭对话框，重新渲染页面
      document.querySelector('#addModal .btn-close').click()
      initStudentList()
    }
  })
})

// 发请求渲染学生信息
tbody.addEventListener('click', function (e) {
  if (!e.target.classList.contains('update')) return
  // 自定义属性获取id
  let id = e.target.getAttribute('data-id')
  axios({
    method: 'get',
    url: '/student/one',
    params: { id }
  }).then(({ data: res }) => {
    if (res.code === 0) {
      // 渲染姓名、年龄、手机号、期望薪资、实际薪资
      updateForm.querySelector('[name="name"]').value = res.data.name
      updateForm.querySelector('[name="age"]').value = res.data.age
      updateForm.querySelector('[name="phone"]').value = res.data.phone
      updateForm.querySelector('[name="salary"]').value = res.data.salary
      updateForm.querySelector('[name="truesalary"]').value = res.data.truesalary
      // 渲染性别
      const gender = updateForm.querySelectorAll('[name="sex"]')
      for (let i = 0; i < gender.length; i++) {
        if (gender[i].value === res.data.sex) {
          gender[i].checked = true
        } else {
          gender[i].checked = false
        }
      }
      // 渲染组号
      const groups = updateForm.querySelectorAll('[name="group"] option')
      for (let i = 0; i < groups.length; i++) {
        if (groups[i].value === res.data.group) {
          groups[i].selected = true
        } else {
          groups[i].selected = false
        }
      }
      // 渲染省市区（此次简单处理，实际需要发送请求）
      updateForm.querySelector('[name="province"]').value = res.data.province
      updateForm.querySelector('[name="city"]').innerHTML = `<option selected value="${ res.data.city }">${ res.data.city }</option>`
      updateForm.querySelector('[name="county"]').innerHTML = `<option selected value="${ res.data.county }">${ res.data.county }</option>`
      // 隐藏域修改id
      updateForm.querySelector('[name="id"]').value = res.data.id
    }
  })
})
// 修改学生信息
updateForm.addEventListener('submit', function (e) {
  e.preventDefault()
  axios({
    url: '/student/update',
    method: 'PUT',
    data: $(this).serialize()
  }).then(({ data: res }) => {
    if (res.code === 0) {
     alert('修改成功')
      document.querySelector('#updateModal .btn-close').click()
      initStudentList()
    }
  })
})